package component.fy.com.common_module.base;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Process;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.multidex.MultiDex;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.view.CropImageView;
import com.mob.MobSDK;
import com.raizlabs.android.dbflow.config.FlowManager;
import com.scwang.smartrefresh.header.StoreHouseHeader;
import com.scwang.smartrefresh.header.TaurusHeader;
import com.scwang.smartrefresh.header.WaveSwipeHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshInitializer;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import component.fy.com.common_module.R;
import component.fy.com.common_module.baidu.LocationService;
import component.fy.com.common_module.constant.AppConstant;
import component.fy.com.common_module.retrofit.RetrofitManager;
import component.fy.com.common_module.utils.LogUtil;
import component.fy.com.common_module.utils.MyUtil;
import component.fy.com.common_module.utils.SharedPreDataBase;
import component.fy.com.common_module.utils.ToastUtil;
import component.fy.com.common_module.widget.GlideImageLoader;

public class BaseCommonApp extends Application {
    private static final String TAG = "BaseCommonApp";
    private static BaseCommonApp baseApp;
    private static Context context;
    private ActivityManager activityManager = null; // activity管理类
    private int maxImgCount = 1;
    private LocationService locationService;
    private Vibrator mVibrator;

    private IWXAPI iwxapi;//微信api
    private boolean isPaid = false;//是否调起支付
    private int WX_payCode = -1;//微信支付返回码 0成功 -1出现错误 -2用户取消

    //static 代码段可以防止内存泄露
    static {
        //设置全局属性
        SmartRefreshLayout.setDefaultRefreshInitializer(new DefaultRefreshInitializer() {
            @Override
            public void initialize(@NonNull Context context, @NonNull RefreshLayout layout) {
                layout.setEnableRefresh(true);//是否启用下拉刷新功能
                layout.setEnableLoadMore(true);//是否启用上拉加载功能
//                layout.setEnablePureScrollMode(false);//是否启用纯滚动模式
                layout.setEnableNestedScroll(false);//是否启用嵌套滚动
                layout.setEnableOverScrollBounce(true);//是否启用越界回弹
                layout.setEnableOverScrollDrag(true);//是否启用越界拖动（仿苹果效果）1.0.4
//                layout.setReboundDuration(800);//回弹动画时长（毫秒）
                layout.setDisableContentWhenRefresh(false);//是否在刷新的时候禁止列表的操作
                layout.setDisableContentWhenLoading(false);//是否在加载的时候禁止列表的操作
            }
        });
        /**
         * 设置全局的Header构建器
         * ClassicsHeader(context) 默认刷新
         * WaveSwipeHeader 全屏滴水
         * WaterDropHeader 水滴效果
         * MaterialHeader google官方swip刷新
         * StoreHouseHeader(context).initWithString("MyComponent", 14).setDropHeight(100).setLineWidth(2) 闪光文字(内容只能为字母，汉字不可以)
         * TaurusHeader 飞机效果
         */
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
//                layout.setPrimaryColorsId(R.color.colorf1f2f7, R.color.colora0a0a0);//全局设置主题颜色
                layout.setPrimaryColorsId(R.color.colorPrimary, R.color.colorWhite);//全局设置主题颜色
                layout.setNoMoreData(false);//恢复没有更多数据的原始状态 1.0.5
                layout.setEnableHeaderTranslationContent(false);//拖动Header的时候是否同时拖动内容（默认true）
//                layout.setDragRate(0.1f);//显示下拉高度/手指真实下拉高度=阻尼效果
                return new WaveSwipeHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
//                layout.setDragRate(0.1f);//显示下拉高度/手指真实下拉高度=阻尼效果
                layout.setEnableScrollContentWhenLoaded(true);//是否在加载完成时滚动列表显示新的内容
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        baseApp = this;
        init();
    }

    private void init() {
        MyUtil.init(this);//初始化MyUtil
        ToastUtil.init(context);//初始化ToastUtil
        SharedPreDataBase.getPreferences(context);//初始化SharedPreDataBase
        activityManager = ActivityManager.getInstance(); // 获得实例
        registerActivityLifecycle();
        //初始化retrofit工具类
        RetrofitManager retrofitManager = RetrofitManager.getInstance();
        retrofitManager.init(context);
        //DBFlow
        FlowManager.init(context);
        //延迟初始化的东西
        new Thread(new Runnable() {
            @Override
            public void run() {
                //设置线程的优先级，不与主线程抢资源
                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                //子线程初始化第三方组件
                try {
                    Thread.sleep(5000);//建议延迟初始化，可以发现是否影响其它功能，或者是崩溃！
                    //图片选择器
                    initImagePicker();
//        // 异常处理，不需要处理时注释掉这两句即可！
////        CrashHandler crashHandler = CrashHandler.getInstance();
////        // 注册crashHandler
////        crashHandler.init(getApplicationContext());
//        crash();//异常处理捕获
                    //实例化微信
                    iwxapi = WXAPIFactory.createWXAPI(context, AppConstant.WX_APP_ID);
                    iwxapi.registerApp(AppConstant.WX_APP_ID);
                    //share sdk三方分享
                    MobSDK.init(context);
                    LogUtil.e(TAG, "延迟启动完成");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        //突破65535的限制
        MultiDex.install(this);
    }

    /**
     * 图片选择器属性设置
     */
    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(true);                           //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(maxImgCount);              //选中数量限制
        imagePicker.setMultiMode(false);                       //图片选择模式 默认true多选,false单选
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }

    /**
     * 异常处理
     */
    private void crash() {
        //捕获主线程异常
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Looper.loop();
                    } catch (Throwable e) {
                        e.printStackTrace();
                        LogUtil.e("捕获到异常", Thread.currentThread().getName() + "在" + e.getStackTrace()[0].getClassName());
                    }
                }
            }
        });
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                e.printStackTrace();
                LogUtil.e("全局捕获到异常", Thread.currentThread().getName() + "在" + e.getStackTrace()[0].getClassName());
            }
        });
    }

    /**
     * 获得当前进程的名字
     *
     * @return
     */
    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        android.app.ActivityManager activityManager = (android.app.ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (android.app.ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    /**
     * 全局Activity生命周期回调监听
     */
    private void registerActivityLifecycle() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                LogUtil.d(TAG, "onActivityCreated__" + activity.getClass().getSimpleName());
                activityManager.addAliveActivity(activity);//加入活动的栈
            }

            @Override
            public void onActivityStarted(Activity activity) {
                LogUtil.d(TAG, "onActivityStarted__" + activity.getClass().getSimpleName());
            }

            @Override
            public void onActivityResumed(Activity activity) {
                LogUtil.d(TAG, "onActivityResumed__" + activity.getClass().getSimpleName());
                activityManager.addFrontActivity(activity);//加入前端可见的栈
                closeKeyboard(activity);
                hideSoftInput(activity);
            }

            @Override
            public void onActivityPaused(Activity activity) {
                LogUtil.d(TAG, "onActivityPaused__" + activity.getClass().getSimpleName());
                activityManager.removeFrontActivity(activity);//移出前端可见
            }

            @Override
            public void onActivityStopped(Activity activity) {
                LogUtil.d(TAG, "onActivityStopped__" + activity.getClass().getSimpleName());
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
                LogUtil.d(TAG, "onActivitySaveInstanceState__" + activity.getClass().getSimpleName());
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                LogUtil.d(TAG, "onActivityDestroyed__" + activity.getClass().getSimpleName());
                activityManager.removeAliveActivity(activity);//移出活动的栈
            }
        });
    }

    /**
     * 关闭软键盘
     */
    protected void closeKeyboard(Activity activity) {
        View view = activity.getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 动态隐藏软键盘
     *
     * @param activity activity
     */
    protected void hideSoftInput(Activity activity) {
        View view = activity.getCurrentFocus();
        if (view == null) {
            view = new View(activity);
        }
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        if (imm == null) {
            return;
        }
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    public static Context getContext() {
        return context;
    }

    public static BaseCommonApp getBaseApp() {
        return baseApp;
    }

    public ActivityManager getActivityManager() {
        return activityManager;
    }

    public void setMaxImgCount(int maxImgCount) {
        this.maxImgCount = maxImgCount;
    }

    public int getMaxImgCount() {
        return maxImgCount;
    }

    public LocationService getLocationService() {
        return locationService;
    }

    //获取微信Sdk实例
    public IWXAPI getIwxapi() {
        return iwxapi;
    }

    public boolean isPaid() {
        return isPaid;
    }

    public void setPaid(boolean paid) {
        isPaid = paid;
    }

    public int getWX_payCode() {
        return WX_payCode;
    }

    public void setWX_payCode(int WX_payCode) {
        this.WX_payCode = WX_payCode;
    }
}
